<?php

/**
 * turnosgenerales actions.
 *
 * @package    SistemaRutasEc
 * @subpackage turnosgenerales
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class turnosgeneralesActions extends sfActions {

    public function executePresentabuses(sfWebRequest $request) {
        if ($request->isXmlHttpRequest()) {
            $id_co = $request->getParameter('idco');
            $tipo = $request->getParameter('tipo');
            
            $buses = Doctrine::getTable('bus')->createQuery('b')
                    ->where('b.id_co = ?', $id_co)
                    ->orderBy('b.disco DESC')
                    ->execute();

            $json_data = array();

            $vectorbus1 = new ArrayObject();
            $vectorbus2 = new ArrayObject();
            $mes = date('n');
            $anio = date('Y');
            foreach ($buses as $bus):

                $fbus = explode("-", $bus->getFechain());
                $afb = $fbus[0];
                $mib = $fbus[1];
                $mescon = 0;
                $aux = $afb;
                $imes = 0;
                $medmes = 0;
                $fmes = 0;
                $tomes = 0;
                $cmes = 0;
                if ($afb == $anio) {
                    if ($mib == $mes) {
                        $cmes = 1;
                    } else {
                        for ($mc = $mib; $mc <= $mes; $mc++) {
                            $cmes++;
                        } $cmes;
                    }$tomes = $cmes;
                } else {
                    for ($mc = $mib; $mc <= 12; $mc++) {
                        $imes++;
                    }
                    $mc = 13;
                    if ($aux + 1 == $anio) {
                        if ($mc == 13) {
                            for ($mc = 1; $mc <= $mes; $mc++) {
                                $fmes++;
                            }
                        }$tomes = $fmes + $imes;
                    } else {
                        while ($aux + 1 != $anio) {
                            if ($mc == 13) {
                                for ($mc = 1; $mc <= 12; $mc++) {
                                    $medmes++;
                                }
                            }
                            $aux++;
                            $mc = 13;
                        }
                    }
                    if ($mc == 13) {
                        for ($mc = 1; $mc <= $mes; $mc++) {
                            $fmes++;
                        }
                    }
                    $tomes = $imes + $medmes + $fmes;
                }

                if ($tomes <= 36) {
                    $vectorbus1[] = $bus;
                } else {
                    $vectorbus2[] = $bus;
                }

            endforeach;
            $vectorbusfinal = new ArrayObject();
            $indicebusfinal = 0;
            if ($tipo == 1) {
                for ($i = 0; $i < count($vectorbus1); $i++) {
                    if ($vectorbus1[$i]->getDisco() > 100) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus1[$i];
                        $indicebusfinal++;
                    }
                }
                for ($i = 0; $i < count($vectorbus1); $i++) {
                    if ($vectorbus1[$i]->getDisco() < 100 && $vectorbus1[$i]->getDisco() >= 10) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus1[$i];
                        $indicebusfinal++;
                    }
                }
                for ($i = 0; $i < count($vectorbus1); $i++) {
                    if ($vectorbus1[$i]->getDisco() < 10) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus1[$i];
                        $indicebusfinal++;
                    }
                }
            } else if ($tipo == 2) {

                for ($i = 0; $i < count($vectorbus2); $i++) {
                    if ($vectorbus2[$i]->getDisco() > 100) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus2[$i];
                        $indicebusfinal++;
                    }
                }
                for ($i = 0; $i < count($vectorbus2); $i++) {
                    if ($vectorbus2[$i]->getDisco() < 100 && $vectorbus2[$i]->getDisco() >= 10) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus2[$i];
                        $indicebusfinal++;
                    }
                }
                for ($i = 0; $i < count($vectorbus2); $i++) {
                    if ($vectorbus2[$i]->getDisco() < 10) {
                        $vectorbusfinal[$indicebusfinal] = $vectorbus2[$i];
                        $indicebusfinal++;
                    }
                }
            }


            foreach ($vectorbusfinal as $bf) {
                $json_data[] = array(
                    'id' => $bf->id_bu,
                    'nombre' => $bf->disco
                );
            }
            return $this->renderText(json_encode($json_data));
        }
        $this->forward404();
    }

    public function executeCreacronograma(sfWebRequest $request) {
        $coop = $request->getParameter('cooperativa');
        $tipo = $request->getParameter('tipo');
        try {
            if (null == $tipo) {
                throw new sfException('Error, no selecciono el tipo ', 1);
            } else {
                $especial = false;
                if ($tipo == 1) {
                    $especial = true;
                }
                $cronograma = Doctrine_Core::getTable('cronograma')->createQuery('c')
                        ->where('c.id_co = ?', $coop)
                        ->andwhere('c.anio = ?', date('Y'))
                        ->andWhere('c.mes = ?', date('m'))
                        ->andWhere('c.especial = ?', $especial)
                        ->fetchOne();
                if (null == $cronograma) {
                    $newcro = new Cronograma();
                    $newcro->setIdCo($coop);
                    $newcro->setMes(date('m'));
                    $newcro->setAnio(date('Y'));
                    $newcro->setEspecial($especial);
                    $newcro->setCreada(TRUE);
                    $newcro->save();
                    $bp = Doctrine_Core::getTable('buspartida')->createQuery('b')->where('b.id_cro = ?', $newcro->id_cro)->fetchOne();
                    if ($newcro->especial == true) {
                        $this->redirect('turnosgenerales/g1?id_cro=' . $newcro->getIdCro() . '&id_bp=' . $bp->getIdBp() . '&buspartida=' . $bp->getNumero() . '&id_co=' . $newcro->getIdCo());
                    } else {
                        $this->redirect('turnosgenerales/g2?id_cro=' . $newcro->getIdCro() . '&id_bp=' . $bp->getIdBp() . '&buspartida=' . $bp->getNumero() . '&id_co=' . $newcro->getIdCo());
                    }
                } else {
                    throw new sfException('Este cronograma ya se creo', 1);
                }
            }
        } catch (sfException $error) {
            return $this->renderText(json_encode(array('status' => 'error', 'message' => $error->getMessage())));
        } catch (Exception $error) {
            $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            return $this->renderText(json_encode(array('status' => 'error', 'message' => 'Ha ocurrido un error al guardar el cronograma')));
        }

        return $this->renderText(json_encode(array('status' => 'ok')));
    }

    public function executeIndex(sfWebRequest $request) {
        $this->idcou = Doctrine_Query::create()
                ->select('c.id_co')
                ->from('Cooperativa c')
                ->where('c.nombre = ?', "Union Cariamanga")
                ->andWhere('c.activo = ?', 1)
                ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
        $this->idcol = Doctrine_Query::create()
                ->select('c.id_co')
                ->from('Cooperativa c')
                ->where('c.nombre = ?', "Loja Internacional")
                ->andWhere('c.activo = ?', 1)
                ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);


        $cronograma = Doctrine_Core::getTable('cronograma')
                ->createQuery('c')
                ->execute();

        if (count($cronograma) >= 4) {
            $this->vacio = false;
            $this->am = $cronograma[0]->getAnio();
            $t = date('Y') - $cronograma[0]->getAnio();
            $this->tf = $t + 1;
        }else{
            $this->vacio = true;            
        }
    }

    public function executeShow(sfWebRequest $request) {
        $this->turno = Doctrine_Core::getTable('turno')->find(array($request->getParameter('id_tu')));
        $this->forward404Unless($this->turno);
    }

    public function executeNew(sfWebRequest $request) {
        $this->form = new turnoForm();
    }

    public function executeCreate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->form = new turnoForm();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($turno = Doctrine_Core::getTable('turno')->find(array($request->getParameter('id_tu'))), sprintf('Object turno does not exist (%s).', $request->getParameter('id_tu')));
        $this->form = new turnoForm($turno);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($turno = Doctrine_Core::getTable('turno')->find(array($request->getParameter('id_tu'))), sprintf('Object turno does not exist (%s).', $request->getParameter('id_tu')));
        $this->form = new turnoForm($turno);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($turno = Doctrine_Core::getTable('turno')->find(array($request->getParameter('id_tu'))), sprintf('Object turno does not exist (%s).', $request->getParameter('id_tu')));
        $turno->delete();

        $this->redirect('turnosgenerales/index');
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $turno = $form->save();

            $this->redirect('turnosgenerales/edit?id_tu=' . $turno->getIdTu());
        }
    }

    //Funcion para guardar turnos especiales con sus respectivos cronogramas y buses de partida
    public function executeG1(sfWebRequest $request) {
        //datos para mantener ordenados cronologicamente
        $this->idcro = $request->getParameter('id_cro');
        $this->idbp = $request->getParameter('id_bp');
        //datos de arranque de creacion de turnos especiales
        $businicial = $request->getParameter('businicial');
        $this->idco = $request->getParameter('id_co');




        $this->rutas = Doctrine::getTable('ruta')->createQuery('r')
                ->where('r.id_co = ?', $this->idco)
                ->execute();
        //buses viejos
        $this->buses = Doctrine::getTable('bus')->createQuery('b')
                ->where('b.id_co = ?', $this->idco)
                ->execute();

        $vectorbus = new ArrayObject();

        $q = Doctrine_Query::create()
                ->from('cronograma c')
                ->where('c.id_cro=?', $this->idcro);
        $cronograma = $q->fetchOne();

        $newcronograma = new Cronograma();
        $newcronograma->setIdCo($this->idco);
        $newcronograma->setEspecial($cronograma->getEspecial());
        if ($cronograma->getMes() == 12) {
            $newcronograma->setMes(1);
            $newcronograma->setAnio($cronograma->getAnio() + 1);
        } else {
            $newcronograma->setMes($cronograma->getMes() + 1);
            $newcronograma->setAnio($cronograma->getAnio());
        }
        $newcronograma->setCreada(TRUE);
        $newcronograma->save();

        $mesactual = $cronograma->getMes();
        $anioactual = $cronograma->getAnio();

        $cob = 0;
        foreach ($this->buses as $bus):
            $fbus = explode("-", $bus->getFechain());
            $afb = $fbus[0];
            $mib = $fbus[1];
            $mescon = 0;
            $aux = $afb;
            $imes = 0;
            $medmes = 0;
            $fmes = 0;
            $tomes = 0;
            $cmes = 0;
            if ($afb == $anioactual) {
                if ($mib == $mesactual) {
                    $cmes = 1;
                } else {
                    for ($mc = $mib; $mc <= $mesactual; $mc++) {
                        $cmes++;
                    } $cmes;
                }$tomes = $cmes;
            } else {
                for ($mc = $mib; $mc <= 12; $mc++) {
                    $imes++;
                }
                $mc = 13;
                if ($aux + 1 == $anioactual) {
                    if ($mc == 13) {
                        for ($mc = 1; $mc <= $mesactual; $mc++) {
                            $fmes++;
                        }
                    }$tomes = $fmes + $imes;
                } else {
                    while ($aux + 1 != $anioactual) {
                        if ($mc == 13) {
                            for ($mc = 1; $mc <= 12; $mc++) {
                                $medmes++;
                            }
                        }
                        $aux++;
                        $mc = 13;
                    }
                }
                if ($mc == 13) {
                    for ($mc = 1; $mc <= $mesactual; $mc++) {
                        $fmes++;
                    }
                }
                $tomes = $imes + $medmes + $fmes;
            }

            if ($tomes <= 36) {
                $vectorbus[$cob] = $bus;
                $cob++;
            }
            $tomes = 0;
        endforeach;
        $vectorbusfinal = new ArrayObject();
        $indicebusfinal = 0;
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() > 100) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() < 100 && $vectorbus[$i]->getDisco() >= 10) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() < 10) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        $vector = new ArrayObject();
        $coun = 0;
        foreach ($this->rutas as $rut):
            $freaux = Doctrine::getTable('frecuencia')->createQuery('f')
                    ->where('f.id_ru = ?', $rut->getIdRu())
                    ->andwhere('f.especial = ?', 1)
                    ->execute();
            foreach ($freaux as $f):
                $vector[$coun] = $f;
                $coun++;
            endforeach;
        endforeach;
        $total = count($vector);
        $vectorfinal = new ArrayObject();
        $menor = 0;
        $i = 0;
        while ($i <= $total) {
            foreach ($vector as $frau):
                if ($frau->getPrioridad() == $i) {
                    $vectorfinal[$i] = $frau;
                }
            endforeach;
            $i++;
        }


        //procesos de almacenamiento de turnos especiales
        $mes = $mesactual;
        $anio = $anioactual;
        $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $anio);
        $arranque = 0;
        for ($j = 0; $j < count($vectorbusfinal); $j++) {
            if ($vectorbusfinal[$j]->getDisco() == $businicial) {
                $arranque = $j;
            }
        }
        for ($i = 1; $i <= $dias; $i++) {
            //echo $i;
            $busespresentados = 0;
            $auxarranque = $arranque;
            for ($k = 0; $k < count($vectorfinal); $k++) {
                if ($auxarranque + $busespresentados == count($vectorbusfinal)) {
                    $auxarranque = 0;
                    $busespresentados = 0;
                }
                //aqui se guarda
                $newt = new Turno();
                $newt->setIdRu($vectorfinal[$k + 1]->getIdRu());
                $newt->setIdFre($vectorfinal[$k + 1]->getIdFr());
                $newt->setIdBu($vectorbusfinal[$auxarranque + $busespresentados]->getIdBu());
                $newt->setIdCo($vectorbusfinal[$auxarranque + $busespresentados]->getIdCo());
                $newt->setHora($vectorfinal[$k + 1]->getHora());
                $newt->setFecha($anio . "-" . $mes . "-" . $i);
                $newt->save();
                //echo $vectorbusfinal[$auxarranque + $busespresentados]->getDisco();
                $busespresentados++;
                //condicional para siguiente bus partida
                if ($i == $dias && $k == 0) {
                    $newbp = new Buspartida();
                    $newbp->setIdCo($vectorbusfinal[$auxarranque + $busespresentados]->getIdCo());
                    $newbp->setIdCro($newcronograma->getIdCro());
                    $newbp->setNumero($vectorbusfinal[$auxarranque + $busespresentados]->getDisco());
                    $newbp->setMes($newcronograma->getMes());
                    $newbp->setAnio($newcronograma->getAnio());
                    $newbp->setEspecial($newcronograma->getEspecial());
                    $newbp->save();
                }
            }
            $arranque--;
            if ($arranque < 0) {
                $arranque = count($vectorbusfinal) - 1;
            }
        }
        $this->redirect('turnosgenerales/index');
    }

//Turnos Normales
    public function executeG2(sfWebRequest $request) {

        //datos para mantener ordenados cronologicamente
        $this->idcro = $request->getParameter('id_cro');
        $this->idbp = $request->getParameter('id_bp');
        //datos de arranque de creacion de turnos especiales
        $businicial = $request->getParameter('businicial');
        $this->idco = $request->getParameter('id_co');



        $this->rutas = Doctrine::getTable('ruta')->createQuery('r')
                ->where('r.id_co = ?', $this->idco)
                ->execute();
        //buses viejos
        $this->buses = Doctrine::getTable('bus')->createQuery('b')
                ->where('b.id_co = ?', $this->idco)
                ->execute();

        $vectorbus = new ArrayObject();

        $q = Doctrine_Query::create()
                ->from('cronograma c')
                ->where('c.id_cro=?', $this->idcro);
        $cronograma = $q->fetchOne();

        $newcronograma = new Cronograma();
        $newcronograma->setIdCo($this->idco);
        $newcronograma->setEspecial($cronograma->getEspecial());
        if ($cronograma->getMes() == 12) {
            $newcronograma->setMes(1);
            $newcronograma->setAnio($cronograma->getAnio() + 1);
        } else {
            $newcronograma->setMes($cronograma->getMes() + 1);
            $newcronograma->setAnio($cronograma->getAnio());
        }
        $newcronograma->setCreada(TRUE);
        $newcronograma->save();

        $mesactual = $cronograma->getMes();
        $anioactual = $cronograma->getAnio();

        $cob = 0;
        foreach ($this->buses as $bus):
            $fbus = explode("-", $bus->getFechain());
            $afb = $fbus[0];
            $mib = $fbus[1];
            $mescon = 0;
            $aux = $afb;
            $imes = 0;
            $medmes = 0;
            $fmes = 0;
            $tomes = 0;
            $cmes = 0;
            if ($afb == $anioactual) {
                if ($mib == $mesactual) {
                    $cmes = 1;
                } else {
                    for ($mc = $mib; $mc <= $mesactual; $mc++) {
                        $cmes++;
                    } $cmes;
                }$tomes = $cmes;
            } else {
                for ($mc = $mib; $mc <= 12; $mc++) {
                    $imes++;
                }
                $mc = 13;
                if ($aux + 1 == $anioactual) {
                    if ($mc == 13) {
                        for ($mc = 1; $mc <= $mesactual; $mc++) {
                            $fmes++;
                        }
                    }$tomes = $fmes + $imes;
                } else {
                    while ($aux + 1 != $anioactual) {
                        if ($mc == 13) {
                            for ($mc = 1; $mc <= 12; $mc++) {
                                $medmes++;
                            }
                        }
                        $aux++;
                        $mc = 13;
                    }
                }
                if ($mc == 13) {
                    for ($mc = 1; $mc <= $mesactual; $mc++) {
                        $fmes++;
                    }
                }
                $tomes = $imes + $medmes + $fmes;
            }

            if ($tomes > 36) {
                $vectorbus[$cob] = $bus;
                $cob++;
            }
            $tomes = 0;
        endforeach;
        $vectorbusfinal = new ArrayObject();
        $indicebusfinal = 0;
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() > 100) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() < 100 && $vectorbus[$i]->getDisco() >= 10) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        for ($i = 0; $i < count($vectorbus); $i++) {
            if ($vectorbus[$i]->getDisco() < 10) {
                $vectorbusfinal[$indicebusfinal] = $vectorbus[$i];
                $indicebusfinal++;
            }
        }
        $vector = new ArrayObject();
        $coun = 0;
        foreach ($this->rutas as $rut):
            $freaux = Doctrine::getTable('frecuencia')->createQuery('f')
                    ->where('f.id_ru = ?', $rut->getIdRu())
                    ->andwhere('f.especial = ?', 0)
                    ->execute();
            foreach ($freaux as $f):
                $vector[$coun] = $f;
                $coun++;
            endforeach;
        endforeach;
        $total = count($vector);
        $vectorfinal = new ArrayObject();
        $menor = 0;
        $i = 0;
        while ($i <= $total) {
            foreach ($vector as $frau):
                if ($frau->getPrioridad() == $i) {
                    $vectorfinal[$i] = $frau;
                }
            endforeach;
            $i++;
        }


        //procesos de almacenamiento de turnos especiales
        $mes = $mesactual;
        $anio = $anioactual;
        $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $anio);
        $arranque = 0;
        for ($j = 0; $j < count($vectorbusfinal); $j++) {
            if ($vectorbusfinal[$j]->getDisco() == $businicial) {
                $arranque = $j;
            }
        }
        for ($i = 1; $i <= $dias; $i++) {
            //echo $i;
            $busespresentados = 0;
            $auxarranque = $arranque;
            for ($k = 0; $k < count($vectorfinal); $k++) {
                if ($auxarranque + $busespresentados == count($vectorbusfinal)) {
                    $auxarranque = 0;
                    $busespresentados = 0;
                }
                //aqui se guarda
                $newt = new Turno();
                $newt->setIdRu($vectorfinal[$k + 1]->getIdRu());
                $newt->setIdFre($vectorfinal[$k + 1]->getIdFr());
                $newt->setIdBu($vectorbusfinal[$auxarranque + $busespresentados]->getIdBu());
                $newt->setIdCo($vectorbusfinal[$auxarranque + $busespresentados]->getIdCo());
                $newt->setHora($vectorfinal[$k + 1]->getHora());
                $newt->setFecha($anio . "-" . $mes . "-" . $i);
                $newt->save();
                //echo $vectorbusfinal[$auxarranque + $busespresentados]->getDisco();
                $busespresentados++;


                //condicional para siguiente bus partida
                if ($i == $dias && $k == 0) {
                    $newbp = new Buspartida();
                    $newbp->setIdCo($vectorbusfinal[$auxarranque + $busespresentados]->getIdCo());
                    $newbp->setIdCro($newcronograma->getIdCro());
                    $newbp->setNumero($vectorbusfinal[$auxarranque + $busespresentados]->getDisco());
                    $newbp->setMes($newcronograma->getMes());
                    $newbp->setAnio($newcronograma->getAnio());
                    $newbp->setEspecial($newcronograma->getEspecial());
                    $newbp->save();
                }
            }
            $arranque--;
            if ($arranque < 0) {
                $arranque = count($vectorbusfinal) - 1;
            }
        }


        $this->redirect('turnosgenerales/index');
    }

}
